//员工管理

/**
 * 添加/编辑视图模型
 */
interface IEmployeeManagentDetailViewModel {
    /**
     * 编号
     */
    id?: string;
    /**
     * 是否禁止输入用户名
     */
    showpassword:boolean;
    /**
     * 密码是否显示
     */
    show:boolean;
    /**
     * 用户名
     */
    userName: string;
    /**
     * 密码
     */
    password?: string;
    /**
     * 重复密码
     */
    rePassword?: string;
    /**
     * 邮箱
     */
    email: string;
    /**
     * 手机号
     */
    phoneNumber: string;
    /**
     * 真实姓名
     */
    realName: string;
    /**
     * 所属部门类别编号
     */
    departmentId?: string;
    /**
     * 性别
     */
    sex:string;
    /**
     * 是否启用
     */
    isEnabled: boolean;
    /**
     * 专员类型
     */
    types: {type:string[]};
    /**
     * 权限值
     */
    auth?: DepartmentAuth
    /**
     * 保存事件
     */
    click: () => void;

    
}

/**
 * 视图模型
 */
interface IEmployeeManagentViewModel extends IBaseViewModel<IEmployeeManagentQueryTerms> {
    /**
     * 填充所属部门下拉
     */
    departmentDropDown: Array<DepartmentListItemResponse>;
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<EmployeeListItemResponse>;
    /**
     * 列表高度
     */
    heightA:number;
    /**
     * 添加/编辑视图
     */
    detail: IEmployeeManagentDetailViewModel;
    /**
     * 添加员工
     */
    addEmployee: () => void;
    /**
     * 选中所属部门下的专员和权限
     */
    selectEmployee:()=>void;
    /**
     * 编辑员工
     */
    editEmployee: (id: string) => void;
    /**
     * 编辑员工权限
     */
    editEmployeeAuthorization:(id)=>void;
    
    //权限列表
    authTree:ListResponse<visualAuthorizationListItemReponse>
    
    /**
     * 折叠h或者展开树
     */
    toggleTree:()=>void
    /**
     * 树的展开状态
     */
    treeExpand:boolean;
       
    authNumbers:{high:number[],middle:number[],low:number[]}
    secAuthTypeTag:string[]

    saveChecked:number;

    saveCheckedAuth:()=>void;
}

/**
 * 查询条件
 */
interface IEmployeeManagentQueryTerms {
    /**
     * 类型
     */
    type: string;
    /**
     * 用户名
     */
    userName: string;
    /**
     * 真实姓名
     */
    realName: string;
    /**
     * 手机号
     */
    phoneNumber: string;
    /**
     * 所属部门类别编号
     */
    departmentId: string;
}

class EmployeeManagentController extends ListController<IEmployeeManagentViewModel, IEmployeeManagentQueryTerms>{
    gridApi: uiGrid.IGridApiOf<EmployeeListItemResponse>;
    selectedRow:any;//选中的那一行
    departmentAuth = {
        HighAuthNumber:null,
        //中等级权限
        MiddleAuthNumber:null,
        //低等级权限
        LowAuthNumber:null,
        //二级权限标签
        SecAuthTypeTag:[]
    }

    constructor($scope: IEmployeeManagentViewModel, private employeeService: IEmployeeService, private departmentService: IDepartmentService,
        private $ngBootbox: BootboxService,private visualAuthorizationService:visualAuthorizationService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();
        this.$scope.addEmployee = this.showAddEmployeeDialog;
        this.$scope.editEmployee = this.showEditEmployeeDialog;
        this.$scope.editEmployeeAuthorization=this.editEmployeeAuthorization
        this.$scope.queryTerms = {
            type: "",
            userName: "",
            realName: "",
            phoneNumber: "",
            departmentId: ""
        };
        this.$scope.toggleTree=()=>{
            this.$scope.treeExpand=!this.$scope.treeExpand
        }
        this.$scope.gridOptions = {
            enableSorting: false,
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            paginationPageSizes: [10, 20, 30],
            columnDefs: [
                { name: "序号", field: "index", enableColumnMenu: false },
                { name: "用户名", field: "userName", enableColumnMenu: false },
                { name: "真实姓名", field: "realName", enableColumnMenu: false },
                { name: "手机号", field: "phoneNumber", enableColumnMenu: false },
                { name: "所属部门", field: "department", enableColumnMenu: false },
                { name: "专员类型", field: "types", enableColumnMenu: false },
                { name: "最后登录时间", field: "lastLoginTime", enableColumnMenu: false },
                {
                    name: "操作",
                    cellFilter: "checkmark",
                    cellTemplate: `<a data-toggle="modal" data-target="#myModal" class="fa fa-edit m-l-xs primary text-info" title="员工编辑" ng-click="grid.appScope.editEmployee(row.entity)">
                                    </a><a data-toggle="modal" data-target="#authModal" class="fa fa-pencil-square m-l-xs primary text-info" title="权限编辑" ng-click="grid.appScope.editEmployeeAuthorization(row.entity)"></a>`,
                    enableColumnMenu: false
                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
            }
        };
        this.query();
        this.loadDepartmentDropDown();
        
        this.$scope.authNumbers={
            high:null,
            middle:null,
            low:null
        }
      
        this.$scope.secAuthTypeTag=[];

        // this.visualAuthorizationService.getList().then(res=>{
        //     this.$scope.authTree=res.data
            
        // })
        this.$scope.saveChecked=0
        this.$scope.saveCheckedAuth=this.saveCheckedAuth;

        
    }

    /**
     * 填充所属部门下拉组件
     */
    loadDepartmentDropDown = () => {
        this.departmentService.getList("", 0, -1).then(result => {
            this.$scope.departmentDropDown = result.data.data;
        });
    }

    loadData(queryTerms: IEmployeeManagentQueryTerms, skip: number, count: number): void {
        this.employeeService.getList(queryTerms.type, queryTerms.userName, queryTerms.realName, queryTerms.phoneNumber, queryTerms.departmentId,null, skip, count).then(result => {
            if (skip == 0) {
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }
            
            this.$scope.gridOptions.totalItems = result.data.total;
            result.data.data.map((item, index) => item.index = skip++ +1);
            this.$scope.gridOptions.data = result.data.data;
            /**
             * 设置列表高度
             */
            this.$scope.heightA = (this.$scope.gridOptions.data.length*39)+80;
        
            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });
    }

    /**
     * 显示添加员工窗口
     */
    showAddEmployeeDialog = () => {
        this.departmentAuth={
            HighAuthNumber:null,
            //中等级权限
            MiddleAuthNumber:null,
            //低等级权限
            LowAuthNumber:null,
            //二级权限标签
            SecAuthTypeTag:[]
        }
        this.$scope.title = "添加员工";
        this.$scope.detail = {
            show:true,
            showpassword:false,
            userName: "",
            password: "",
            rePassword: "",
            email: "",
            phoneNumber: "",
            realName: "",
            departmentId: "",
            sex: "true",
            isEnabled: true,
            types: {type:[]},
            auth:this.departmentAuth,
            click: this.addEmployee
        };
        this.$scope.selectEmployee = this.selectEmployee;
    }

    addEmployee = () => {
        if (!$("#employeeForm").valid()) { return };
        this.$ngBootbox.confirm("确定保存该数据吗？").then(e => {
            if(this.isSexResponse( this.$scope.detail.sex)){
                this.employeeService.add(
                    this.$scope.detail.userName,
                    this.$scope.detail.password,
                    this.$scope.detail.rePassword,
                    this.$scope.detail.email,
                    this.$scope.detail.phoneNumber,
                    this.$scope.detail.realName,
                    this.$scope.detail.sex,
                    this.$scope.detail.isEnabled,
                    this.$scope.detail.departmentId,
                    this.$scope.detail.types.type,
                    this.departmentAuth
                ).then(result => {
                    this.reload();
                    $('#myModal').modal('hide');
                });
            }
        });
    }

    /**
     * 选中所属部门下的专员和权限
     */
    selectEmployee =() =>{
        let selectedDepartment=this.$scope.departmentDropDown.filter(item=>item.id===this.$scope.detail.departmentId)[0];
        // console.log(selectedDepartment);
        if(selectedDepartment){
            this.departmentAuth={
                HighAuthNumber:selectedDepartment.highAuthNumber,
                MiddleAuthNumber:selectedDepartment.middleAuthNumber,
                LowAuthNumber:selectedDepartment.lowAuthNumber,
                SecAuthTypeTag:selectedDepartment.secAuthorizationTypeTag
            }
            var typeList=selectedDepartment.typeList;
            typeList=typeList.filter(type=>{return type!=='3'&&type!=='8'})
            this.$scope.detail.types={type:typeList}
        }else{
            this.departmentAuth={
                HighAuthNumber:null,
                MiddleAuthNumber:null,
                LowAuthNumber:null,
                SecAuthTypeTag:[]
            }
            this.$scope.detail.types={type:[]}
        }
        // this.departmentService.getDetail(this.$scope.detail.departmentId).then(res=>{
        //     this.$scope.detail.types.type = res.data.types;
        //     this.$scope.detail.roles.role = res.data.roles;
        // });
        
        
    }

    isSexResponse(response: string | boolean): response is boolean {
        return (<boolean>response) !== undefined;
    }
    /**
     * 显示编辑员工窗口
     */
    showEditEmployeeDialog = (row: any) => {

        this.departmentAuth={HighAuthNumber:row.highAuthNumber,
                            MiddleAuthNumber:row.middleAuthNumber ,
                            LowAuthNumber:row.lowAuthNumber,
                            SecAuthTypeTag:row.secAuthorizationTypeTag};
        let id=row.id;
        this.$scope.title = "编辑员工";
        $("#authorizationRepeat").find("input[name='itemCheckN']").prop("checked", false);
        //清除验证规则
        $('#table_employeeManagent_detail_password').removeClass('required');
        $('#table_employeeManagent_detail_rePassword').removeClass('required');
        $(".error").removeClass("error");
        this.employeeService.getDetail(id).then(result => {
            this.$scope.detail = {
                id: id,
                show:false,
                showpassword:true,
                userName: result.data.userName,
                email: result.data.email,
                phoneNumber: result.data.phoneNumber,
                realName: result.data.realName,
                sex: String(result.data.sex),
                isEnabled: result.data.isEnabled,
                departmentId: result.data.userGroupId,
                auth:{
                    HighAuthNumber:row.highAuthNumber,
                    MiddleAuthNumber:row.middleAuthNumber,
                    LowAuthNumber:row.lowAuthNumber,
                    SecAuthTypeTag:row.secAuthorizationTypeTag
                },
                types: {type:result.data.types},
                click: this.editEmployee
            };
        });
        this.$scope.selectEmployee = this.selectEmployee;
    }

    editEmployee = ()=> {
        if(!this.$scope.detail.phoneNumber || this.$scope.detail.phoneNumber.length!=11){
            this.$ngBootbox.alert('请输入正确的11位手机号');
            return;
        }
        this.$ngBootbox.confirm("确定保存该数据吗？").then(e => {
            if(this.isSexResponse(this.$scope.detail.sex)){
                this.employeeService.edit(
                    this.$scope.detail.id,
                    this.$scope.detail.password,
                    this.$scope.detail.email,
                    this.$scope.detail.phoneNumber,
                    this.$scope.detail.realName,
                    this.$scope.detail.sex,
                    this.$scope.detail.isEnabled,
                    this.$scope.detail.departmentId,
                    
                    this.$scope.detail.types.type,
                    this.departmentAuth
                ).then(result => {
                    this.reload(this.$scope.gridOptions.paginationCurrentPage);
                    $('#myModal').modal('hide');
                });
            }
        });
    }

    /**
     * 打开编辑员工权限弹框
     */
    editEmployeeAuthorization=(row)=>{
        // console.log(row);
        this.visualAuthorizationService.getList(row.id,null).then(res=>{
            this.$scope.authTree=res.data
        })
        this.$scope.treeExpand=false;
        this.selectedRow=row;
    }
    /**
     * 保存员工权限更改
     */
    saveCheckedAuth=()=>{
        // this.$scope.saveChecked++;
        
        this.$ngBootbox.confirm('确认保存数据吗').then(e=>{
            // console.log(this.$scope.authNumbers,this.$scope.secAuthTypeTag);
            let checkedNumbers={high:[],middle:[],low:[]},secAuthTags=[];
            
            let nodes=this.$scope.authTree.data;
            nodes&&nodes.forEach(firstAuth=>{
                firstAuth.secAuthTypeList&&firstAuth.secAuthTypeList.forEach(secNode=>{
                    secNode.visualAuthList&&secNode.visualAuthList.forEach(thNode=>{
                        if(thNode.isShow){
                            // checkedNumbers.push(thNode.authNumber);
                            let key=['high','middle','low'][thNode.level-1]  ;
                            if(key){
                                // console.log(checkedNumbers);
                                checkedNumbers[key].push(thNode.number);
                            }
                            
                            if(secAuthTags.indexOf(thNode.secAuthorizationTypeTag)===-1){
                                secAuthTags.push(thNode.secAuthorizationTypeTag);
                            }
                        }
                    })
                })
                
            })
                
                
            
            this.$scope.authNumbers=checkedNumbers;
            this.$scope.secAuthTypeTag=secAuthTags;

            let authObj={
                HighAuthNumber:this.$scope.authNumbers.high,
                //中等级权限
                MiddleAuthNumber:this.$scope.authNumbers.middle,
                //低等级权限
                LowAuthNumber:this.$scope.authNumbers.low,
                //二级权限标签
                SecAuthTypeTag:this.$scope.secAuthTypeTag
            }
            this.employeeService.editAuth(this.selectedRow.id,authObj).then(res=>{
                // console.log(res)
                this.reload(this.$scope.gridOptions.paginationCurrentPage);
                $('#authModal').modal('hide');
                
            })

        })
       

    }
}

angular.module('tms').controller('employeeManagentController', ['$scope', 'employeeService', 'departmentService', '$ngBootbox','visualAuthorizationService', EmployeeManagentController]);